package org.elec.mac.inter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.entity.OAuthToken;
import org.elec.mac.entity.SClientWx;
import org.elec.mac.entity.SMachine;
import org.elec.mac.exception.ErrorCode;
import org.elec.mac.exception.ErrorMsg;
import org.elec.mac.service.SClientWxService;
import org.elec.mac.service.SMachineService;
import org.elec.mac.utils.WebKit;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Slf4j
@Controller
@RequestMapping(value = "/inter")
public class RegisterController extends InterController {

    @Autowired
    private SClientWxService sClientWxService;

    @Autowired
    private SMachineService sMachineService;

    @RequestMapping(value = "/register.do")
    private void registerHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        int code = 0;
        result.put("code", code);
        result.put("msg", "成功");
        try {
            String sign = request.getParameter("sign");
            if(StringUtils.isNotBlank(sign)) {
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("sign", sign);
                SMachine sMachine = sMachineService.get(param);
                if(sMachine != null) {
                    result = authToken(result);
                    result.put("mach", sMachine.getId());
                } else {
                    result.put("code", ErrorCode.ERR_FAILED);
                    result.put("msg", "没有匹配机台");
                }
            } else {
                JSONObject json = new JSONObject(WebKit.requestJson(request));
                String reg = (String) json.get("reg");
                JSONArray jsonArray = (JSONArray) json.get("reginfo");
                JSONObject reginfo = jsonArray.getJSONObject(0);

                if(reg.contains("AlipayClient")) {
                    log.info("[json]=" + json.toString());
                } else if(reg.contains("MicroMessenger")) {
                    Object obj = this.jsonToObject(reginfo, new SClientWx());
                    if(obj == null) {
                        code = ErrorCode.ERR_CLIENT_REGISTER;
                        result.put("code", code);
                        result.put("msg", ErrorMsg.errorMessage(code));
                    }
                    if(code == 0) {
                        SClientWx client = (SClientWx) obj;
                        if(sClientWxService.update(client) == 0) {
                            client.setCreateTime(new Date());
                            sClientWxService.insert(client);
                        }
                        result = authToken(result);
                    }
                } else {
                    result = authToken(result);
                }
            }
        } catch(Exception ex) {
            log.error("微信数据上传错误", ex);
            code = ErrorCode.ERR_FAILED;
            result.put("code", code);
            result.put("msg", ex.getMessage());
        }
        response.getWriter().write(result.toString());
    }

    /**
     * @param result
     * @return
     */
    public JSONObject authToken(JSONObject result) {
        try {

            OAuthToken authToken = new OAuthToken();
            authToken.setAccess_token(RandomStringUtils.randomAlphanumeric(20));
            authToken.setToken_type("example");
            authToken.setExpires_in(60L * 60L * 24L * 30L * 1000L);
            authToken.setRefresh_token(RandomStringUtils.randomAlphanumeric(20));
            authToken.setLogin_time(Calendar.getInstance().getTimeInMillis());

            EhCacheCacheManager manager = cacheConfiguration
                    .ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
            Cache cache = manager.getCache("authTokenCache");
            cache.put(authToken.getAccess_token(), authToken);

            result.put("accesstoken", authToken.getAccess_token());

        } catch(Exception ex) {
            log.error("密码验证错误", ex);
            result.put("success", ErrorCode.ERR_REGISTER_LOGIN);
            result.put("msg", ErrorMsg.errorMessage(ErrorCode.ERR_REGISTER_LOGIN));
        }
        return result;
    }
}
